<?php
error_reporting(E_ALL ^ E_NOTICE);

use Net\Connection;
use Net\Event;

require_once './Net/Connection.php';
require_once './Net/Event.php';

$server = new Connection;

$server
    ->onError(function(Event $e) {
        echo "服务错误: {$e->getErrorCode()} {$e->getErrorMessage()}\n";
        die;
    })
    
    //服务已就绪
    ->onReady(function() use($server) {
        $bindInfo = $server->getBindInfo();
        echo "服务已就绪, 监听地址 {$bindInfo['address']}:{$bindInfo['port']}\n";
    })
    
    //新连接进入
    ->onNewConnect(function (Event $e) use($server) {
        $connection = $e->getConnection();
        echo "新连接: $connection\n";
    
        $connection
            ->onRecv(function(Event $e) use($connection, $server) {
                $message = $e->getMessage();
                
                if(strtolower($message) == 'exit') {
                    $server->close();
                    return;
                }
                
                echo "收到来自客户端{$connection}的数据: {$message}\n";
                $connection->send('数据已收到!');
            })
            ->onClose(function() use($connection) {
                echo "$connection 已关闭\n";
            })
        ;
    })
    
    //服务退出
    ->onClose(function() {
        echo "服务已退出\n";
        die;
    })
;


$server->listening('0.0.0.0', 30001);

Connection::dispatch();
